package ch.zbw.pra.sysventory.network.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import ch.zbw.pra.sysventory.domain.model.Scanversion;
import ch.zbw.pra.sysventory.domain.scanner.Scanner;
import ch.zbw.pra.sysventory.domain.util.MyLogger;
import ch.zbw.pra.sysventory.ui.AgentMainFrame;
import ch.zbw.pra.sysventory.ui.InfoLabel;

public class TCPClient implements Runnable {

	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TCPClient.class);

	private int port;
	private Socket socket;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	private String servername;
	private Scanner scanner;
	private boolean isScanning;

	public TCPClient(int port, Scanner scanner) {
		this.port = port;
		this.scanner = scanner;
	}

	public void run() {
		while (true) {
			try {
				// Create a connection to the server socket on the server
				// application
				servername = AgentMainFrame.getInstance().getIPAdressFromTextField();

				socket = new Socket(servername, port);
				MyLogger.logDebug(log, "Connected to: " + socket.getRemoteSocketAddress());
				oos = new ObjectOutputStream(socket.getOutputStream());
				MyLogger.logDebug(log, "Warte auf Scanstart");
				InfoLabel.setTextInfoLabel("Warte auf Scanstart...");
				ois = new ObjectInputStream(socket.getInputStream());
				isScanning = ois.readBoolean();
				MyLogger.logDebug(log, "Scanvorgang: " + isScanning);

				if (isScanning) {
					Scanversion scanversion = scanner.wmiscan();

					// Send a Scanversion to the Server application
					MyLogger.logDebug(log,
							"Try to send Scanversion from: " + socket.getLocalSocketAddress()
									+ "to: " + socket.getRemoteSocketAddress());
					InfoLabel.setTextInfoLabel("Sende Scan an Server: "
							+ socket.getRemoteSocketAddress());

					oos.writeObject(scanversion);
					MyLogger.logDebug(log,
							"Scanversion sent to: " + socket.getRemoteSocketAddress());
					InfoLabel.setTextInfoLabel("Scan erfolgreich gesendet!!!");

					// Tell Server, submit is finished
					oos.writeBoolean(true);

					oos.flush();
					oos.close();
				}

			} catch (UnknownHostException e) {
				MyLogger.logError(log, e.toString());
			} catch (IOException e) {
				MyLogger.logError(log, e.toString());
				InfoLabel.setTextInfoLabel("Keine Verbindung zum Server!");
			}
		}

	}

	public void disconnect() {
		try {
			if (socket != null) {
				socket.close();
				MyLogger.logDebug(log, "Socket closed.");
			}
		} catch (IOException e) {
			MyLogger.logError(log, e.toString());
		}
	}
}